<template>
  <div class="app-container">
    <ThePageHead>请假申请列表</ThePageHead>
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit"
                 @click="handleCreate">
        申请休假
      </el-button>
    </div>


    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column type="index" label="序号" width="50px" align="center"/>
      <el-table-column label="请假类型" align="center">
        <template slot-scope="{row}">
          <span>{{ getholidaytypestr(row.applytype) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假原因" align="center">
        <template slot-scope="{row}">
          <span>{{ row.applyformemo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假日" align="center">
        <template slot-scope="{row}">
          <span>{{ row.holidaydatestr }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.updated_at | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center">
        <template slot-scope="{row}">
          <span>{{ row.checker == null || row.checker === '' ? '--': row.checker }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.checkstatus | statusFilter" :title="row.checkmemo">
            {{ row.checker == null || row.checker === '' ? '未审核' : getcheckstatusstr(row.checkstatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="center">
        <template slot-scope="{row}">
          <span  v-if="row.checker == null || row.checker === ''">--</span>
          <span  v-if="row.checker != null && row.checker !== ''">{{ row.checktime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" v-if="row.checker==null || row.checker===''" size="mini" @click="handleUpdate(row)">
            修改申请
          </el-button>
          <el-button v-if="row.checker==null|| row.checker===''" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList" align="center"/>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" style="padding: 40px;">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="160px"
               style="width: 95%;">
        <el-form-item label="假期类型：" prop="applytype">
          <el-select v-model="temp.applytype" placeholder="请选择假期类型" clearable>
            <el-option
              v-for="h in holidaytypes"
              :key="h.key"
              :label="h.display_name"
              :value="h.key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请假原因：" prop="applyformemo">
          <el-input v-model="temp.applyformemo" style="width:100%;"/>
        </el-form-item>

        <el-form-item label="请假日：" prop="holidaydates">
          <el-popover
            placement="right"
            width="600"
            trigger="click"
          >
            <el-calendar>
              <template
                slot="dateCell"
                slot-scope="{data}"
              >
                <p class="innerDate" @click="changeCheck(data.day)">
                  {{ data.day.split('-').slice(1).join('-') }} {{ temp.holidaydates.indexOf(data.day)>-1 ? '✔️' : '' }}
                </p>
              </template>
            </el-calendar>
            <el-button slot="reference" type="warning">选择时间（多选）</el-button>
          </el-popover>
        </el-form-item>
        <!--
        <el-form-item label="请假日：" prop="holidaydatestr">
            <el-input v-model="temp.holidaydatestr" style="width:100%;" />
          </el-form-item>
          -->
        <div
          v-if="temp.holidaydates.length > 0"
          style="margin-top: 25px;margin-left:40px;"
        >
          <!-- <el-button class="filter-item" type="primary" icon="el-icon-plus" size="small" plain @click="handleAdd">
          添加
        </el-button> -->

          <el-table
            :data="temp.datelist"
            :border="true"
            style="width: 100%"
          >
            <el-table-column type="index" label="序号" width="50px" align="center"/>
            <el-table-column label="请假日" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.holidaydate }}</span>
              </template>
            </el-table-column>
            <el-table-column label="是否全天" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.datetype" width="200px">
                  <el-option
                    v-for="h in datetypes"
                    :key="h.key"
                    :label="h.display_name"
                    :value="h.key"></el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="saveData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getholidays, addapplyfor, updateapplyfor, deleteapplyfor} from '@/api/holiday'
  import waves from '@/directive/waves' // waves directive
  import {parseTime} from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination

  /*
  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})
  */
  export default {
    name: 'holidayapplylist',
    components: {Pagination},
    directives: {waves},
    filters: {
      statusFilter(status) {
        if (status == null || status === '')
          return 'info'

        const statusMap = {
          ok: 'success',
          fail: 'danger'
        }

        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          key: ''//,
          //title: undefined,
          //type: undefined,
          //sort: '+id'
        },
        textMap: {
          update: '申请休假（编辑）',
          create: '申请休假'
        },
        checkstatus: [
          {key: 'ok', display_name: '通过'},
          {key: 'fail', display_name: '不通过'}
        ],
        datetypes: [
          {key: 'all', display_name: '全天'},
          {key: 'am', display_name: '上午'},
          {key: 'pm', display_name: '下午'}
        ],
        holidaytypes: [
          {key: 'adjust', display_name: '调休'},
          {key: 'paid', display_name: '带薪假'},
          {key: 'affairs', display_name: '事假'},
          {key: 'sick', display_name: '病假'}
        ],
        dialogFormVisible: false,
        dialogStatus: '',
        dialogPvVisible: false,
        pvData: [],
        temp: {
          applyforid: '',
          applyformemo: '',
          applytype: '',
          holidaydates: [],
          holidaydatestr: '',
          datelist: []
        },
        rules: {
          applyformemo: [{required: true, message: '请假原因不能为空！', trigger: 'change'}],
          applytype: [{required: true, message: '请假类型不能为空！', trigger: 'change'}]
        }/*,
      //importanceOptions: [1, 2, 3],
      //calendarTypeOptions,
      //sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      //statusOptions: ['published', 'draft', 'deleted'],
      //showReviewer: false,
      downloadLoading: false*/
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getcheckstatusstr(key) {
        let h = this.checkstatus.find(p => p.key == key)
        return h.display_name
      },
      getholidaytypestr(key) {
        let h = this.holidaytypes.find(p => p.key == key)
        return h.display_name
      },
      getList() {
        this.listLoading = true
        getholidays(this.listQuery).then(response => {
          this.list = response.data.data
          this.total = response.page.count

          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1000)
        })
      },
      changeCheck(day) {
        if (this.disabled) {
          return
        }
        const arr = this.temp.holidaydates
        const datelist = this.temp.datelist
        if (arr.includes(day)) {
          // eslint-disable-next-line no-extend-native
          Array.prototype.remove = function (val) {
            var index = this.indexOf(val)
            if (index > -1) {
              this.splice(index, 1)
            }
          }
          arr.remove(day)
          for(let i in datelist) {
            if (datelist[i].holidaydate === day) {
              datelist.remove(datelist[i])
            }
          }
        } else {
          arr.push(day)
          datelist.push({holidaydate:day, datetype:"all"});
        }
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        //this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleDelete(row, index) {
        this.$confirm("确定删除吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }).then(() => {
          deleteapplyfor({
            applyforid: row.applyforid
          }).then(() => {
            this.getList()
            this.$notify({
              title: 'Success',
              message: '删除成功！',
              type: 'success',
              duration: 2000
            })
          })
        }).catch(()=>{});;
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      changeSatus(t) {
        //updateDetail(t).then((res) => {
        //  this.fetchData()
        //})
      },
      resetTemp() {
        this.temp = {
          applyforid: '',
          applyformemo: '',
          applytype: '',
          holidaydates: [],
          holidaydatestr: '',
          datelist: []
        }
      },
      saveData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dialogStatus === 'create') {
              addapplyfor(this.temp).then(() => {
                this.list.unshift(this.temp)
                this.dialogFormVisible = false
                this.getList()
                this.$notify({
                  title: 'Success',
                  message: '申请休假保存成功！',
                  type: 'success',
                  duration: 2000
                })
              })
            } else {
              updateapplyfor(this.temp).then(() => {
                this.list.unshift(this.temp)
                this.dialogFormVisible = false
                this.getList()
                this.$notify({
                  title: 'Success',
                  message: '编辑休假申请成功！',
                  type: 'success',
                  duration: 2000
                })
              })
            }

          }
        })
      }
      /*,

      handleModifyStatus(row, status) {
        this.$message({
          message: '操作Success',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },




      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            updateArticle(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },

      handleFetchPv(pv) {
        fetchPv(pv).then(response => {
          this.pvData = response.data.pvData
          this.dialogPvVisible = true
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
          const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }

      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }*/
    }
  }
</script>
<style scoped lang="scss">
  .el-form-item label:after {
    content: "";
    display: inline-block;
    width: 100%;
  }

  .el-form-item__label {
    text-align: justify;
    height: 50px;
  }

  .el-form-item.is-required .el-form-item__label:before {
    content: none !important;
  }

  .innerDate {
    width: 100%;
    height: 100%;
  }
</style>
